﻿using Sobiens.SPCamlStudio.Common;
using Sobiens.SPCamlStudio.Entities;
using Sobiens.SPCamlStudio.Entities.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace Sobiens.SPCamlStudio.UI.Controls
{
    /// <summary>
    /// Interaction logic for CodeWizardForm.xaml
    /// </summary>
    public partial class CodeWizardForm : HostControl
    {
        private List<IQueryPanel> _QueryPanels = null;
        public CodeWizardForm()
        {
            InitializeComponent();
        }

        protected override void OnLoad()
        {
            base.OnLoad();
            this.InitializeForm();
        }

        private void InitializeForm()
        {
            this.OKButtonSelected += ViewRelationForm_OKButtonSelected;
        }

        void ViewRelationForm_OKButtonSelected(object sender, EventArgs e)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode contentNode = null;
            var assembly = Assembly.Load("Sobiens.SPCamlStudio.UI");
            var resourceName = "Sobiens.SPCamlStudio.UI.Resources.SPOnlineWebpart.dwp";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                string xmlString = reader.ReadToEnd();
                xDoc.LoadXml(xmlString);
                foreach (XmlNode node in xDoc.ChildNodes[1].ChildNodes)
                {
                    if (node.Name.Equals("Content", StringComparison.InvariantCultureIgnoreCase) == true)
                    {
                        contentNode = node;
                        break;
                    }
                }
            }

            StringBuilder sb = new StringBuilder();
            foreach (object t in ViewRelationsTreeView.Items)
            {
                TreeViewItem treeviewItem = (TreeViewItem)t;
                ViewRelation viewRelation = (ViewRelation)treeviewItem.Tag;
                string appendix = viewRelation.ID.ToString().Replace('-', '_');
                sb.AppendLine("<div id='soby_GridDiv" + appendix + "'></div>");
            }
            sb.AppendLine("<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>");
            sb.AppendLine("<script language='javascript' src='https://cdn.rawgit.com/serkantsamurkas/sobiens/master/soby.spservice.js'></script>");
            sb.AppendLine("<script language='javascript' src='https://cdn.rawgit.com/serkantsamurkas/sobiens/master/soby.ui.components.js'></script>");
            sb.AppendLine("<script language='javascript'>");
            sb.Append(GenerateGridsScript(ViewRelationsTreeView.Items));
            sb.AppendLine("</script>");
            string path = "c:\\temp";
            contentNode.InnerText = sb.ToString();

            xDoc.Save(path + "\\soby_test.dwp");
//            File.WriteAllText(path + "\\soby_test.dwp", sb.ToString());
            Process.Start("Explorer.exe", path);
        }

        public void Initialize(List<IQueryPanel> queryPanels) 
        {
            _QueryPanels = queryPanels;
            ViewComboBox.Items.Clear();
            foreach(IQueryPanel queryPanel in _QueryPanels){
                ViewComboBox.Items.Add(new ComboBoxItem()
                {
                    Content = queryPanel.FileName,
                    Tag = queryPanel
                });
            }
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if(ViewComboBox.SelectedItem ==null)
                return;

            TreeViewItem selectedTreeViewItem = null;
            IQueryPanel masterQueryPanel = null;
            Guid masterViewRelationID = Guid.Empty;
            if (ViewRelationsTreeView.SelectedItem != null)
            {
                selectedTreeViewItem = (TreeViewItem)ViewRelationsTreeView.SelectedItem;
                Guid detailQueryPanelID = ((ViewRelation)selectedTreeViewItem.Tag).DetailQueryPanelID;
                masterViewRelationID = ((ViewRelation)selectedTreeViewItem.Tag).ID;
                masterQueryPanel = ApplicationContext.Current.SPCamlStudio.QueriesPanel.GetQueryPanel(detailQueryPanelID);
                //masterQueryPanel = (IQueryPanel)selectedTreeViewItem.Tag;
            }
            ComboBoxItem selectedComboBoxItem = (ComboBoxItem)ViewComboBox.SelectedItem;
            IQueryPanel detailQueryPanel = (IQueryPanel)selectedComboBoxItem.Tag;
            ViewRelation viewRelation = ViewRelation.NewViewRelation();
            viewRelation.MasterViewRelationID = masterViewRelationID;
            viewRelation.DetailQueryPanelID = detailQueryPanel.ID;
            viewRelation.Name = detailQueryPanel.FileName;
            viewRelation.DetailSiteUrl = detailQueryPanel.AttachedObject.GetWebUrl();
            viewRelation.DetailListName = detailQueryPanel.AttachedObject.GetListName();
            if (selectedComboBoxItem.Parent == null)
                viewRelation.IsRoot = true;

            TreeViewItem newTreeViewItem = new TreeViewItem()
                {
                    Header = viewRelation.Name,
                    Tag = viewRelation
                };
            if (selectedTreeViewItem == null)
            {
                ViewRelationsTreeView.Items.Add(newTreeViewItem);
            }
            else
            {
                ViewRelationForm viewRelationForm = new ViewRelationForm();
                viewRelationForm.Initialize(masterQueryPanel, detailQueryPanel);
                viewRelationForm.Tag=viewRelation;
                if (viewRelationForm.ShowDialog(this.ParentWindow, "View Relation") == true)
                {
                    selectedTreeViewItem.Items.Add(newTreeViewItem);
                }
            }

        }

        private string GenerateGridsScript(ItemCollection items) 
        {
            StringBuilder sb = new StringBuilder();
            foreach (object t in items)
            {
                TreeViewItem treeviewItem = (TreeViewItem)t;
                ViewRelation viewRelation = (ViewRelation)treeviewItem.Tag;
                IQueryPanel queryPanel = ApplicationContext.Current.SPCamlStudio.QueriesPanel.GetQueryPanel(viewRelation.DetailQueryPanelID);
                string appendix = viewRelation.ID.ToString().Replace('-', '_') ;
                sb.AppendLine("var dataSourceBuilder" + appendix + " = new soby_CamlBuilder('" + viewRelation.DetailListName + "', '', 5, '" + viewRelation.DetailSiteUrl + "');");
                sb.AppendLine("dataSourceBuilder" + appendix + ".Filters = new CamlFilters(false);");
                sb.AppendLine("var spService" + appendix + " = new soby_SharePointService(dataSourceBuilder" + appendix + ");");
                sb.AppendLine("var sobyGrid" + appendix + " = new soby_DataGrid('#soby_GridDiv" + appendix + "', '" + viewRelation.DetailListName + "', spService" + appendix + ", 'There is no record found.')");
                List<CamlFieldRef> viewFields = queryPanel.GetViewFields();
                foreach(CamlFieldRef viewField in viewFields){
                    sb.AppendLine("dataSourceBuilder" + appendix + ".AddViewField('" + viewField.Name + "', '" + viewField.Name + "', CamlFieldTypes.Text);");
                    sb.AppendLine("sobyGrid" + appendix + ".AddColumn('" + viewField.Name + "', '" + viewField.DisplayName + "');");
                }

                foreach (object z in treeviewItem.Items)
                {
                    TreeViewItem treeviewItem1 = (TreeViewItem)z;
                    ViewRelation viewRelation1 = (ViewRelation)treeviewItem1.Tag;
                    if((from h in viewFields
                                where h.Name == viewRelation1.MasterFieldValueName
                                select h).ToList().Count == 0)
                    {
                        sb.AppendLine("dataSourceBuilder" + appendix + ".AddViewField('" + viewRelation1.MasterFieldValueName + "', '" + viewRelation1.MasterFieldValueName + "', CamlFieldTypes.Text);");
                    }
                }

                if(string.IsNullOrEmpty(viewRelation.MasterFieldDisplayName) == false)
                {
                    sb.AppendLine("sobyGrid" + viewRelation.MasterViewRelationID.ToString().Replace('-', '_') + ".AddDataRelation('" + viewRelation.MasterFieldDisplayName + "', '" + viewRelation.MasterFieldValueName + "', sobyGrid" + appendix + ".GridID, '" + viewRelation.DetailFieldName + "')");
                }
                else
                {
                    sb.AppendLine("sobyGrid" + appendix + ".Initialize(true);");
                }

                sb.Append(GenerateGridsScript(treeviewItem.Items));
            }

            return sb.ToString();
        }

    }
}
